﻿

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Demo</title>
    <link href="//unpkg.com/layui@2.10.1/dist/css/layui.css" rel="stylesheet">
    <style>
        .layui-input {width: 200px;}
        .layui-form-select {width: 200px;}
        .layui-form-select dl {min-width: 200px;}
    </style>
</head>
<body>
    <form class="layui-form" id="myForm">
        <!-- 用户名 -->
        <div class="layui-form-item">
            <label class="layui-form-label" style="width:auto">用户名</label>
            <div class="layui-input-block">
                <input type="text" name="userName" lay-verify="required|username" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>

        <!-- 部门下拉框 -->
        <div class="layui-form-item">
            <label class="layui-form-label" style="width:auto">部门</label>
            <div class="layui-input-block">
                <select name="depId" lay-filter="aihao" id="deptSelect">
                    <option value="">--请选择部门--</option>
                </select>
            </div>
        </div>



        <!-- 角色下拉框 -->
        <div class="layui-form-item">
            <label class="layui-form-label">角色</label>
            <div class="layui-input-block">
                <select name="roleId" lay-filter="aihao" id="deprole">
                    <option value="">--请选择部门--</option>
                </select>
            </div>
        </div>


        <!-- 密码 -->
        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-inline layui-input-wrap">
                <input type="password" name="password" lay-verify="required|pass" placeholder="请输入" autocomplete="off" lay-affix="eye" class="layui-input">
            </div>
            <div class="layui-form-mid layui-text-em">6到12位字符（数字+字母+特殊字符）</div>
        </div>

        <!-- 昵称 -->
        <div class="layui-form-item">
            <label class="layui-form-label">昵称</label>
            <div class="layui-input-block">
                <input type="text" name="nickName" lay-verify="required|nickname" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>

        <!-- 性别 -->
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="radio" name="sex":value="false" title="男" checked>
                <input type="radio" name="sex" value="true" title="女">
            </div>
        </div>


        <label style="width:auto" class="layui-form-label" title="所属省/市/区">
            所属省/市/区
        </label>
        <div class="layui-input-block">
         
            <div class="layui-input-inline" style="width: 30%;">
                <select name="provinceId" id="province" lay-filter="province" lay-search=""></select>
            </div>
            <div class="layui-input-inline" style="width: 30%;">
                <select name="cityId" id="city" lay-filter="city" lay-search=""></select>
            </div>
            <div class="layui-input-inline" style="width: 30%;">
                <select name="countyId" id="area" lay-filter="area" lay-search=""></select>
            </div>
        </div>


        <!-- 详细地址 -->
        <div class="layui-form-item layui-form-text">
            <label style="width:auto" class="layui-form-label">详细地址</label>
            <div class="layui-input-block">
                <textarea name="hamletName" placeholder="请输入内容" class="layui-textarea"></textarea>
            </div>
        </div>

        <!-- 按钮组 -->
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="submit" class="layui-btn" lay-submit lay-filter="demo1">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>

    <!-- 依赖库 -->

    <script type="text/javascript" src="~/lib/area.js"></script>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


    <script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>


    <script>
        layui.use(['form', 'layer', 'jquery'], function() {
            var form = layui.form,
                layer = layui.layer;
                var $ = layui.$;



                function loadAddress(array, lables, notId) {
                var s = '<option value="">请选择</option>';
                if (array) {
                    for (var i = 0; i < array.length; i++) {
                        var obj = array[i];
                        s += '<option value="' + obj.address + '" lay-id="' + obj.code + '">' + obj.address + '</option>';
                    }
                }
                $(notId).empty();
                $(lables).html(s);
                form.render("select");
            }



            // 省级选择，获取市
            form.on('select(province)', function (data) {
                var array = layArea.getCityList(data.value);
                loadAddress(array, "#city", "#city,#area")
            });

            // 市级选择，获取地区/县
            form.on('select(city)', function (data) {
                var name1 = $("#province").val();
                var array = layArea.getAreaList(name1, data.value);
                loadAddress(array, "#area", "#area")
            });

            // 加载省份
            loadAddress(layArea.array, "#province", "#city,#area");

            form.on('submit(saveCustomer)', function (data) {
                // 这里可以通过AJAX将数据发送到后台
                layer.msg('提交成功');
                return false;
            });





            // ========== 部门加载逻辑（保留原有） ==========
            function loadDepartments() {
                $.ajax({
                    //url: "https://localhost:7174/api/Message/GetDepart",
                    url: "@ViewBag.BaseUrl/T5/Message/GetDepart",
                    type: "GET",
                    headers: { 'Authorization': 'Bearer YOUR_TOKEN' },
                    success: function(res) {
                        if (res.code === 0 && res.data.length > 0) {
                            const options = res.data.map(item => 
                                `<option value="${item.departId}">${item.departName}</option>`
                            ).join('');
                            $('#deptSelect').html(`<option value="">--请选择部门--</option>${options}`);
                            form.render('select');
                        }
                    }
                });
            }
            $(loadDepartments);


                        // ========== 角色加载逻辑（保留原有） ==========
            function RoleDepartments() {
                $.ajax({
                    //url: "https://localhost:7174/api/Message/GetRoleAll",
                    url: "@ViewBag.BaseUrl/T5/Message/GetRoleAll",
                    type: "GET",
                    headers: { 'Authorization': 'Bearer YOUR_TOKEN' },
                    success: function(res) {
                        if (res.code === 0 && res.data.length > 0) {
                            const options = res.data.map(item =>
                                `<option value="${item.roleId}">${item.roleName}</option>`
                            ).join('');
                            $('#deprole').html(`<option value="">--请选择角色--</option>${options}`);
                            form.render('select');
                        }
                    }
                });
            }
            $(RoleDepartments);




             form.on('submit(demo1)', function(data){
            // 防止重复提交
            var isSubmitting = false;

            if(isSubmitting) return false;
            isSubmitting = true;

            // 获取表单数据
            var formData = {
                userName: data.field.userName,
                depId: data.field.depId,
                roleId:data.field.roleId,
                password: data.field.password,
                nickName: data.field.nickName,
                sex: data.field.sex === "true", // 转换为布尔值
                provinceId: data.field.provinceId,
                cityId: data.field.cityId,
                countyId: data.field.countyId,
                hamletName: data.field.hamletName,
                createName: "admin",
                createTime: new Date().toISOString()
            };

            console.log("表单数据:", formData);

            // 显示加载中提示
            var loadingIndex = layer.load(1, {
                shade: [0.1, '#fff']
            });

            // AJAX提交
            $.ajax({
                //url: "https://localhost:7272/api/Message/AddUser",
                url: "@ViewBag.BaseUrl/T6/Message/AddUser",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify(formData),
                dataType: 'json',
                complete: function() {
                    layer.close(loadingIndex);
                    isSubmitting = false; // 重置提交状态
                },
                success: function(res) {
                    if(res.code === 212) {
                        layer.msg('提交成功', {icon: 1, time: 2000}, function(){
                            document.getElementById("myForm").reset();
                            form.render();
                        });
                    } else {
                        layer.msg(res.msg || '提交失败', {icon: 2, time: 3000});
                    }
                },
                error: function(xhr, status, error) {
                    var errorMsg = '请求出错: ';
                    if(xhr.responseJSON && xhr.responseJSON.message) {
                        errorMsg += xhr.responseJSON.message;
                    } else {
                        errorMsg += error;
                    }
                    layer.msg(errorMsg, {icon: 2, time: 5000});
                }
            });

            return false; // 阻止表单默认提交
        });
    });
    </script>
</body>
</html>
